/*******************************************************************************
*	                           oled spi.c
*******************************************************************************/
#include "bsp.h"
#include "swspi.h"

#define PORT_PIN_CTEAT
#include "pinfun.h"

port_out_pin_make(swspi_cs, PB, 12);
port_out_pin_make(swspi_sck, PB, 13);
port_in_pin_make(swspi_miso, PB, 14);
port_out_pin_make(swspi_mosi, PB, 15);

/*****************************************************************************
* @brief   hal init.
* @param   none
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
void bsp_sw_spi_init(void)
{
	swspi_cs.dir_out_pp();
	swspi_cs.en();
	swspi_miso.dir_in_up();
	swspi_mosi.dir_out_pp();
	swspi_sck.dir_out_pp();
}

/*****************************************************************************
* @brief   spi hal.
*****************************************************************************/
#define DLY NOP5
static void cs_out_high(void){swspi_cs.en(); DLY();}
static void cs_out_low(void){swspi_cs.dis(); DLY();}
static void sck_out_high(void){swspi_sck.en();DLY();}
static void sck_out_low(void){swspi_sck.dis();DLY();}
static void mosi_out_high(void){swspi_mosi.en();DLY();}
static void mosi_out_low(void){swspi_mosi.dis();DLY();}
static uu8 miso_st_get(void){DLY(); return swspi_miso.in_st();}

spi_cfg_type sw_spi_cfg = 
{
	.cs_out_high = cs_out_high,
	.cs_out_low = cs_out_low,
	.sck_out_high = sck_out_high,
	.sck_out_low = sck_out_low,
	.mosi_out_high = mosi_out_high,
	.mosi_out_low = mosi_out_low,
	.miso_st_get = miso_st_get
};

/*****************************************************************************
* @brief   spi data read.
*****************************************************************************/
uint8_t bsp_sw_spi_rb(void)
{
	return sw_spi8_rw(&sw_spi_cfg, 0xFF);
}

void bsp_sw_spi_wb(uint8_t dataW)
{
	sw_spi8_rw(&sw_spi_cfg,  dataW);
}

/*****************************************************************************
* @brief   spi data write.
*****************************************************************************/
void bsp_sw_spi_write(const uint8_t *dataw, uint32_t Len)
{
	while(Len--)
	{
		bsp_sw_spi_wb(*dataw++);
	}
}

/*****************************************************************************
* @brief   spi data read.
*****************************************************************************/
void bsp_sw_spi_read(uint8_t *datar, uint32_t Len)
{
	while(Len--)
	{
		*datar = bsp_sw_spi_rb();
		datar++;
	}
}
